﻿using JNPF.Basics.Logic;
using JNPF.Basics.Models;
using JNPF.Basics.Models.WeChat.Dtos.MPMenu;
using JNPF.Utils;
using JNPF.Utils.Controller;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JNPF.Basics.Controller
{
    /// <summary>
    /// 公众号菜单
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018-09-10 
    /// </summary>
    [Route("api/WeChat/MPMenu")]
    public class MPMenuController : BaseApiController
    {
        private MPMenuBll mPMenuBll = new MPMenuBll();
        private MPEventContentBll mPEventContentBll = new MPEventContentBll();

        #region GET
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResult> GetList([FromQuery] KeywordInput input)
        {
            try
            {
                var data = await mPMenuBll.GetList();
                if (!string.IsNullOrEmpty(input.keyword))
                {
                    data = data.TreeWhere(t => t.Name.Contains(input.keyword), t => t.Id, t => t.ParentId);
                }
                var output = data.Select(x => new MPMenuListOutput()
                {
                    fullName = x.Name,
                    type = x.Type,
                    content = x.Content,
                    url = x.Url,
                    id = x.Id,
                    parentId = x.ParentId
                }).ToList();
                return Success(new { list = output.ToTree() });
            }
            catch (Exception)
            {
                return Error("操作过于频繁");
            }
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("Selector")]
        public async Task<ResponseResult> GetListAll()
        {
            var data = await mPMenuBll.GetList();
            var treeList = data.Select(x => new MPMenuSelectorOutput()
            {
                fullName = x.Name,
                id = x.Id,
                parentId = x.ParentId
            }).ToList();
            return Success(new { list = treeList.ToTree() });
        }

        /// <summary>
        /// 重复验证（名称）
        /// </summary>
        /// <param name="fullName">名称</param>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        [HttpGet("IsExistByFullName")]
        public async Task<ResponseResult> IsExistByFullName(string fullName, string id)
        {
            var data = await mPMenuBll.IsExistByFullName(fullName, id);
            return Success(data);
        }

        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ResponseResult> GetInfo(string id)
        {
            var data = await mPEventContentBll.GetInfo(id);
            return Success(data.MapTo<MPMenuInfoOutput>());
        }
        #endregion

        #region POST
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> Create([FromBody] MPMenuCrInput input)
        {
            var entity = input.MapTo<MPMenuModel>();
            entity.Name = input.fullName;
            int strLen = Encoding.Default.GetBytes(entity.Name).Length;
            if (entity.ParentId == "0")
            {
                if (strLen > 16)
                {
                    return Error("操作失败，一级菜单文字最多不能超过16字节");
                }
            }
            else
            {
                if (strLen > 40)
                {
                    return Error("操作失败，二级菜单文字最多不能超过40字节");
                }
            }
            if (entity.Type == "view")
            {
                entity.Content = null;
            }
            else if (entity.Type == "click")
            {
                entity.Url = null;
            }
            else
            {
                entity.Content = null;
                entity.Url = null;
            }
            var menuList = await mPMenuBll.GetList();
            menuList.Add(entity);
            if (menuList.FindAll(t => t.ParentId == "0").Count > 3)
            {
                return Error("操作失败，最多3个一级菜单");
            }
            else if (menuList.FindAll(t => t.ParentId == entity.ParentId).Count > 5)
            {
                return Error("操作失败，最多5个二级菜单");
            }
            else
            {
                //同步List
                await mPMenuBll.SyncMenu(menuList);
                await mPMenuBll.Create(entity);
                return Success("操作成功");
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ResponseResult> Update(string id, [FromBody] MPMenuUpInput input)
        {
            var entity = input.MapTo<MPMenuModel>();
            if (entity.Type == "view")
            {
                entity.Content = null;
            }
            else if (entity.Type == "click")
            {
                entity.Url = null;
            }
            else
            {
                entity.Content = null;
                entity.Url = null;
            }
            var menuList = await mPMenuBll.GetList();
            var menuModel = menuList.Find(m => m.Id == id);
            menuList.Remove(menuModel);
            menuList.Add(entity);
            //同步List
            await mPMenuBll.SyncMenu(menuList);
            await mPMenuBll.Update(id, entity);
            return Success("操作成功");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResponseResult> Delete(string id)
        {
            var menuList = await mPMenuBll.GetList();
            var menuModel = menuList.Find(m => m.Id == id);
            menuList.Remove(menuModel);
            //同步List
            await mPMenuBll.SyncMenu(menuList);
            await mPMenuBll.Delete(id);
            return Success("操作成功");
        }
        #endregion
    }
}